<!DOCTYPE html>
<html lang="zh-CH" >
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="author" content="" />
	
	
	
	<title>Unity3D AssetBundle 框架整理（一）自动做标记 ｜ zansimple</title>
	
    
    
    <meta name="description" content="前言 之前也做了一些关于 AssetBundle 的了解，专门在官方网站上查了文档，现在我们开始着手造一个自己的轮子了，对就是 AssetBundle 框架，首先我们要做的是将想要打包的资源做上标记。
目的 就是提高开发效率，不用手动一个一个自己做标记，如果文件少的话还好，要是很多的话手动打标记不知道要打到什么时候。
思路 其实可想而知，自动打标记无非就是给我一个资源路径，我通过这个路径将里面的所有的资源文件遍历一遍，然后通过 AssetImporter 这个 API 设置每个文件的 assetbundleName 和 assetBundleVariant 属性，当然在设置属性的时候提前分好类，决定将哪些资源放到一个 AssetBundle 包内。然后记录一下要打多少个 AssetBundle 包，以及该包所在的目录，方便以后查找加载。
如果对文件操作不熟悉的百度一下，可以帮助理解。
代码  # region 自动做标记[MenuItem(&amp;quot;AssetBundle/Set AssetBundle Lables&amp;quot; ,false , 100)]public static void SetAssetBundleLables(){//移除掉所有没有使用的标记AssetDatabase.RemoveUnusedAssetBundleNames();string assetDirectory = &amp;quot;Assets/Res&amp;quot;;DirectoryInfo directoryInfo = new DirectoryInfo(assetDirectory);DirectoryInfo[] scenesDirectories = directoryInfo.GetDirectories();foreach (var tempDir in scenesDirectories){string sceneDirectory = assetDirectory &#43; &amp;quot;/&amp;quot; &#43; tempDir.Name;DirectoryInfo sceneDirectoryInfo = new DirectoryInfo(sceneDirectory);if (sceneDirectoryInfo == null){Debug." />
    

    

	
    
    <link rel="shortcut icon" href="https://lenzan.github.io/images/favicon.ico" />

    <link rel="stylesheet" type="text/css" media="screen" href="https://lenzan.github.io/css/normalize.css" />
    <link rel="stylesheet" type="text/css" media="screen" href="https://cdn.jsdelivr.net/npm/animate.css@4.1.0/animate.min.css" />
    <link rel="stylesheet" type="text/css" media="screen" href="https://lenzan.github.io/css/zozo.css" />
	<link rel="stylesheet" type="text/css" media="screen" href="https://cdn.jsdelivr.net/npm/remixicon@2.5.0/fonts/remixicon.css" />
    <link rel="stylesheet" type="text/css" media="screen" href="https://lenzan.github.io/css/highlight.css" />

    
    
</head>

<body>
    <div class="main animate__animated animate__fadeInDown">
        <div class="nav_container animated fadeInDown">
    <div class="site_nav" id="site_nav">
        <ul>
            
            <li>
                <a href="/">首页</a>
            </li>
            
            <li>
                <a href="/">unity</a>
            </li>
            
            <li>
                <a href="/">归档</a>
            </li>
            
            <li>
                <a href="/">关于</a>
            </li>
            
        </ul>
    </div>
    <div class="menu_icon">
        <a id="menu_icon"><i class="ri-menu-line"></i></a>
    </div>
</div>
        <div class="header animated fadeInDown">
    <div class="site_title_container">
        <div class="site_title">
            <h1>
                <a href="https://lenzan.github.io/">
                    <span>zansimple</span>
                    <img src="https://lenzan.github.io/images/logo.svg" />
                </a>
            </h1>
        </div>
        <div class="description">
            <p class="sub_title">专注于Unity虚拟现实开发，游戏开发</p>
            <div class="my_socials">
                
                <a href="https://lenzan.github.io/index.xml" type="application/rss+xml" title="rss" target="_blank"><i
                        class="ri-rss-fill"></i></a>
            </div>
        </div>
    </div>
</div>
        <div class="content">
            <div class="post_page">
                <div class="post animate__animated animate__fadeInDown">
                    <div class="post_title post_detail_title">
                        <h2><a href='/posts/assetbundle-manager/auto-setLable/'>Unity3D AssetBundle 框架整理（一）自动做标记</a></h2>
                        <span class="date">2018.07.18</span>
                    </div>
                    <div class="post_content markdown"><!-- raw HTML omitted -->
<h2 id="前言">前言</h2>
<p>之前也做了一些关于 AssetBundle 的了解，专门在官方网站上查了文档，现在我们开始着手造一个自己的轮子了，对就是 AssetBundle 框架，首先我们要做的是将想要打包的资源做上标记。</p>
<h3 id="目的">目的</h3>
<p>就是提高开发效率，不用手动一个一个自己做标记，如果文件少的话还好，要是很多的话手动打标记不知道要打到什么时候。</p>
<h3 id="思路">思路</h3>
<p>其实可想而知，自动打标记无非就是给我一个资源路径，我通过这个路径将里面的所有的资源文件遍历一遍，然后通过 AssetImporter 这个 API 设置每个文件的 assetbundleName 和 assetBundleVariant 属性，当然在设置属性的时候提前分好类，决定将哪些资源放到一个 AssetBundle 包内。然后记录一下要打多少个 AssetBundle 包，以及该包所在的目录，方便以后查找加载。</p>
<p>如果对文件操作不熟悉的百度一下，可以帮助理解。</p>
<h3 id="代码">代码</h3>
<pre><code> # region 自动做标记
[MenuItem(&quot;AssetBundle/Set AssetBundle Lables&quot; ,false , 100)]
public static void SetAssetBundleLables()
{
    //移除掉所有没有使用的标记
    AssetDatabase.RemoveUnusedAssetBundleNames();
    string assetDirectory = &quot;Assets/Res&quot;;
    DirectoryInfo directoryInfo = new DirectoryInfo(assetDirectory);
    DirectoryInfo[] scenesDirectories = directoryInfo.GetDirectories();
    foreach (var tempDir in scenesDirectories)
    {
        string sceneDirectory = assetDirectory + &quot;/&quot; + tempDir.Name;
        DirectoryInfo sceneDirectoryInfo = new DirectoryInfo(sceneDirectory);
        if (sceneDirectoryInfo == null)
        {
            Debug.Log(sceneDirectoryInfo + &quot;不存在&quot;);
            return;
        }
        else
        {
            Dictionary&lt;string , string&gt; namePathDictionary = new Dictionary&lt;string, string&gt;();
            int index = sceneDirectory.LastIndexOf(&quot;/&quot;);
            string sceneName = sceneDirectory.Substring(index + 1);
            OnSceneFileSystemInfo(sceneDirectoryInfo , sceneName , namePathDictionary);
            OnWriteConfig(sceneName , namePathDictionary);
        }
    }
    AssetDatabase.Refresh();
    Debug.Log(&quot;设置标记成功...&quot;);
}

/// &lt;summary&gt;
/// 记录配置文件
/// &lt;/summary&gt;
/// &lt;param name=&quot;sceneDirectory&quot;&gt;&lt;/param&gt;
/// &lt;param name=&quot;namePathDictionary&quot;&gt;&lt;/param&gt;
private static void OnWriteConfig(string sceneName , Dictionary&lt;string , string&gt; namePathDictionary)
{
    string path = Application.dataPath + &quot;/AssetBundles/&quot; + sceneName ;
  
    if (!Directory.Exists(path)) Directory.CreateDirectory(path);
    Debug.Log(path);
    using (FileStream fs = new FileStream(path + &quot;/Record.txt&quot;, FileMode.OpenOrCreate , FileAccess.Write))
    {
        using (StreamWriter sw = new StreamWriter(fs))
        {
            sw.WriteLine(namePathDictionary.Count);
            foreach (KeyValuePair&lt;string , string&gt; kv in namePathDictionary)
            {
                Debug.Log(kv.Value);
                sw.WriteLine(kv.Key+&quot;/&quot;+kv.Value);
            }
        }
    }
}

private static void OnSceneFileSystemInfo(FileSystemInfo fileSystemInfo , string sceneNama , Dictionary&lt;string, string&gt; namePathDictionary)
{
    if (!fileSystemInfo.Exists)
    {
        Debug.Log(fileSystemInfo + &quot;不存在&quot;);
        return;
    }
    DirectoryInfo directoryInfo = fileSystemInfo as DirectoryInfo;

    FileSystemInfo[] fileSystemInfos = directoryInfo.GetFileSystemInfos();
    foreach (var systemInfo in fileSystemInfos)
    {
        FileInfo fileInfo = systemInfo as FileInfo;
        if (fileInfo == null)
        {
            OnSceneFileSystemInfo(systemInfo, sceneNama , namePathDictionary);
        }
        else
        {
            SetLables(fileInfo, sceneNama , namePathDictionary);
        }
    }
}
/// &lt;summary&gt;
/// 修改资源 assetbundle lables
/// &lt;/summary&gt;
private static void SetLables(FileInfo fileInfo , string sceneName , Dictionary&lt;string, string&gt; namePathDictionary)
{
    if(fileInfo.Extension == &quot;.meta&quot;)return;
    string bundleName = GetBundleName(fileInfo , sceneName);
    int index = fileInfo.FullName.IndexOf(&quot;Assets&quot;);
    string assetPath = fileInfo.FullName.Substring(index);
    AssetImporter assetImporter = AssetImporter.GetAtPath(assetPath);
    assetImporter.assetBundleName = bundleName;
    if (fileInfo.Extension == &quot;.unity&quot;)
        assetImporter.assetBundleVariant = &quot;u3d&quot;;
    else
        assetImporter.assetBundleVariant = &quot;assetbundle&quot;;
    string folderName;
    if (bundleName.Contains(&quot;/&quot;))
        folderName = bundleName.Split('/')[1];
    else
        folderName = bundleName;
    string bundlePath = assetImporter.assetBundleName + &quot;.&quot; + assetImporter.assetBundleVariant;
    if (!namePathDictionary.ContainsKey(folderName))
        namePathDictionary.Add(folderName, bundlePath);
}

private static string GetBundleName(FileInfo fileInfo, string sceneName)
{
    string path = fileInfo.FullName;
    int index = path.IndexOf(sceneName) + sceneName.Length;
    string bundlePath = path.Substring(index + 1);
    bundlePath = bundlePath.Replace(@&quot;\&quot;, &quot;/&quot;);
    if (bundlePath.Contains(&quot;/&quot;))
    {
        string[] tmp = bundlePath.Split('/');
        
        return sceneName + &quot;/&quot; + tmp[0];
    }
    return sceneName;
}

#endregion
</code></pre>
<h3 id="一键打包">一键打包</h3>
<p>根据刚才我们设置好的标记，Unity 就可以识别到我们想要打包的资源，官方有个打包 AssetBundle 的插件（ AssetBundle Browser ），你可以用那款插件打包。
我自己也写了一个但是不是很好，这个东西可以用官方的代替。也可以根据自己的需求改一下。我这里选择的压缩方式是不压缩（ BuildAssetBundleOptions.None 这个选项）。</p>
<pre><code>#region 打包
static void BuildAssetBundles(string outPath , BuildTarget target)
{
    if (!Directory.Exists(outPath)) Directory.CreateDirectory(outPath);
    BuildPipeline.BuildAssetBundles(outPath, BuildAssetBundleOptions.None, target);
}

[MenuItem(&quot;AssetBundle/CreateAndroidAssetBundles&quot;, false, 200)]
public static void BuildAndroidAssetBundles()
{
    string outPath = &quot;Assets/AssetBundles/Android&quot;;
    BuildAssetBundles(outPath , BuildTarget.Android);
}

[MenuItem(&quot;AssetBundle/CreateIOSAssetBundles&quot;, false, 201)]
public static void BuildIOSAssetBundles()
{
    string outPath = &quot;Assets/AssetBundles/IOS&quot;;
    BuildAssetBundles(outPath, BuildTarget.iOS);
}

[MenuItem(&quot;AssetBundle/CreateStandaloneWindows64AssetBundles&quot;, false, 202)]
public static void BuildStandaloneWindows64AssetBundles()
{
    string outPath = &quot;Assets/AssetBundles/StandaloneWindows64&quot;;
    BuildAssetBundles(outPath, BuildTarget.StandaloneWindows64);
}
#endregion
</code></pre>
<h3 id="一键删除">一键删除</h3>
<p>这个就简单了，把目标路径删除掉就 OK 了。</p>
<pre><code>#region 一键删除
[MenuItem(&quot;AssetBundle/Delete All&quot;)]
static void DeletAssetBundles()
{
    string outPuth = &quot;Assets/AssetBundles&quot;;
    Directory .Delete(outPuth , true);
    File.Delete(outPuth+ &quot;.meta&quot;);
    AssetDatabase.Refresh();
}
#endregion
</code></pre>
</div>
                    <div class="post_footer">
                        
                        <div class="meta">
                            <div class="info">
                                <span class="field tags">
                                    <i class="ri-stack-line"></i>
                                    
                                    <a href="https://lenzan.github.io/tags/Unity3D/">Unity3D</a>
                                    
                                    <a href="https://lenzan.github.io/tags/AssetBundle/">AssetBundle</a>
                                    
                                </span>
                            </div>
                        </div>
                        
                    </div>
                </div>
                
                
            </div>
        </div>
    </div>
    <a id="back_to_top" href="#" class="back_to_top"><span>△</span></a>
    <footer class="footer">
    <div class="powered_by">
        <a href="https://varkai.com">Designed by VarKai,</a>
        <a href="http://www.gohugo.io/">Proudly published with Hugo</a>
    </div>

    <div class="footer_slogan">
        <span></span>
    </div>
</footer>
    <script src="https://lenzan.github.io/js/jquery-3.5.1.min.js"></script>
<link href="https://lenzan.github.io/css/fancybox.min.css" rel="stylesheet">
<script src="https://lenzan.github.io/js/fancybox.min.js"></script>
<script src="https://lenzan.github.io/js/zozo.js"></script>






</body>

</html>